package com.framework.utils.StarPos;


import com.alibaba.fastjson.JSONObject;
import com.framework.utils.MD5Util;
import org.apache.http.HttpEntity;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;


public class StarposVerify {

    //private final static String BaseUrl = "http://sandbox.starpos.com.cn/emercapp";
    private final static String BaseUrl="https://gateway.starpos.com.cn/emercapp";
    //private final static String orgNo = "518";
    private final static String orgNo="1467";

    //private final static String key = "9773BCF5BAC01078C9479E67919157B8";
    private final static String key="6928A794B9F3ACFF82E9C0FCE18C4449";
    /**
     * 发送请求
     */
    public  static String sendVerify(String mercId, String log_no) {
        StringBuffer sb=new StringBuffer();
        try {

            SortedMap<String, Object> map = new TreeMap<>();
            map.put("orgNo", orgNo);
            map.put("serviceId", "6060603");
            map.put("mercId", mercId);
            map.put("log_no", log_no);
            map.put("version", "V1.0.1");
            Set<String> keys = map.keySet();
            Iterator<String> it = keys.iterator();
            System.out.print("验签字段:  ");
            String waitSign = "";
            while (it.hasNext()) {
                String keytemp = it.next();

                waitSign += String.valueOf(map.get(keytemp));

                System.out.print(keytemp + ",");

            }
            System.out.println();
            waitSign += key;

            String signValue = MD5Util.MD5(waitSign);
            System.out.println(signValue);

            //创建连接
            URL url = new URL(BaseUrl);

            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestMethod("POST");
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestProperty("Content-Type", "application/json; charset=GBK");
            connection.connect();

            //POST请求
            DataOutputStream out = new DataOutputStream(connection.getOutputStream());


            map.put("signValue", signValue);


            String content;
            content = JSONObject.toJSONString(map);

            out.write(content.getBytes("GBK"));//这样可以处理中文乱码问题

            //  out.writeBytes(content);//这个中文会乱码
            out.flush();
            out.close();

            //读取响应
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    connection.getInputStream(), "gbk"));
            String lines;
            while ((lines = reader.readLine()) != null) {
                lines = new String(lines.getBytes(), StandardCharsets.UTF_8);

                sb.append(lines);

                System.out.println(lines);
            }

            //System.out.println( new String(sb.toString().getBytes("gbk"),"utf-8"));
            reader.close();
            // 断开连接
            connection.disconnect();

        } catch (UnsupportedEncodingException e) {
            return sb.toString();
        } catch (ProtocolException e) {
            return sb.toString();
        } catch (MalformedURLException e) {
            return sb.toString();
        } catch (IOException e) {
            return sb.toString();
        }
        return sb.toString();
    }

    /**
     * 获取区域码
     * @param prov_nm
     * @param city_nm
     * @return
     */
    public  static String stoecode(String prov_nm, String city_nm) {
        StringBuffer sb=new StringBuffer();
        String body="";
        try {

            SortedMap<String, Object> map = new TreeMap<>();
            map.put("orgNo", orgNo);
            map.put("serviceId", "6060206");

            map.put("version", "V1.0.1");
            Set<String> keys = map.keySet();
            Iterator<String> it = keys.iterator();
            System.out.print("验签字段:  ");
            String waitSign = "";
            while (it.hasNext()) {
                String keytemp = it.next();

                waitSign += String.valueOf(map.get(keytemp));

                System.out.print(keytemp + ",");

            }
            System.out.println();
            waitSign += key;
            System.out.print("验签内容:  ");
            System.out.println(waitSign);
            String signValue= MD5Util.MD52(waitSign);
            System.out.println(signValue);

            HttpEntity entity1 = null;
            HttpClient httpClient = new DefaultHttpClient();
            map.put("prov_nm", prov_nm);
            map.put("city_nm", city_nm);
            map.put("signValue",signValue);
            String content;
            content=JSONObject.toJSONString(map);
            HttpPost post = new HttpPost(BaseUrl);
            //utf-8项目发送gbk中文 我不知道为啥这样写，不过没得错
            StringEntity entity = new StringEntity(content, ContentType.create("application/json","gbk"));
            post.setEntity(entity);
            //post.setHeader("Content-Type", "application/json;charset=GBK");

            //logger.info("post:" + post);

            org.apache.http.HttpResponse httpresponse = httpClient.execute(post);

            entity1 = httpresponse.getEntity();
            body = EntityUtils.toString(entity1, "gbk");
            System.out.println(body);


        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return body;
    }
}
